package com.swjd.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.swjd.po.User;

public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		// 获取访问的URL
		String url = request.getRequestURI();
		// 判断访问URL里面是否包含"/login"字符串，有则返回ture(即判断是否访问登陆页面，如果访问的是登陆页面，直接放行，让用户登陆)
		if (url.indexOf("/login") > 0) {
			return true;
		}
		// 如果访问的不是登陆页面，则判断用户是否已经登陆
		// 获取session对象
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("SESSION");
		//判断session中的user是否为空（是否登陆），有数据则放行
		if (user!=null) {
			return true;
		}
		//访问的既不是登陆页面，又没有登陆，则拦截，禁止访问,并转发到登陆页面
	    request.setAttribute("msg", "还没有登陆，请先登陆！");
	    request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
		return false;
	}

}
